package com.xyhuo.leetcode;

import java.util.*;

public class WordDictionary {

    private Map<Integer, Set<String>> map;

    public WordDictionary() {
        map = new HashMap<>();
    }

    public void addWord(String word) {
        int len = word.length();
        if (map.containsKey(len)) {
            map.get(len).add(word);
        } else {
            Set<String> list = new HashSet<>();
            list.add(word);
            map.put(len, list);
        }
    }

    public boolean search(String word) {
        int len = word.length();
        if (!map.containsKey(len)) {
            return false;
        }
        Set<String> list = map.get(len);
        if (word.indexOf(".") == -1) {
            return list.contains(word);
        } else {
            for (String str : list) {
                if (match(str, word)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean match(String word1, String word2) {
        int len = word1.length();
        char[] word1CharArray = word1.toCharArray();
        char[] word2CharArray = word2.toCharArray();
        for (int i = 0; i < len; i++) {
            if (word2CharArray[i] == '.' || word1CharArray[i] == '.') {
                continue;
            }
            if (word1CharArray[i] != word2CharArray[i]) {
                return false;
            }
        }
        return true;
    }
}
